package com.yangmf.auto_message_handle.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ContentHighlightUtil {
    
    /**
     * 高亮显示匹配的关键字
     * @param content 原始内容
     * @param keyword 搜索关键字
     * @param beforeLength 关键字前显示字符数
     * @param afterLength 关键字后显示字符数
     * @return 高亮处理后的内容片段
     */
    public static String highlightContent(String content, String keyword, int beforeLength, int afterLength) {
        if (content == null || keyword == null || keyword.isEmpty()) {
            return content;
        }
        
        int index = content.toLowerCase().indexOf(keyword.toLowerCase());
        if (index == -1) {
            // 如果没找到关键字，返回部分内容
            int endIndex = Math.min(beforeLength + afterLength, content.length());
            return content.substring(0, endIndex) + (content.length() > endIndex ? "..." : "");
        }
        
        int start = Math.max(0, index - beforeLength);
        int end = Math.min(content.length(), index + keyword.length() + afterLength);
        
        StringBuilder result = new StringBuilder();
        if (start > 0) {
            result.append("...");
        }
        
        String beforeText = content.substring(start, index);
        String matchedText = content.substring(index, index + keyword.length());
        String afterText = content.substring(index + keyword.length(), end);
        
        result.append(beforeText)
              .append("<span style='background-color: yellow;'>")
              .append(matchedText)
              .append("</span>")
              .append(afterText);
              
        if (end < content.length()) {
            result.append("...");
        }
        log.info("高亮处理成功,返回内容为{}",result);
        return result.toString();
    }
}
